package com.example.teachingSystem.service.impl;

import com.example.teachingSystem.pojo.form.upload.UploadResponse;
import com.example.teachingSystem.pojo.vo.UploadVo;
import com.example.teachingSystem.service.UploadService;
import com.example.teachingSystem.utils.result.Result;
import com.example.teachingSystem.utils.result.ResultCodeEnum;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

import java.io.IOException;

@Service
public class UploadServiceImpl implements UploadService {
    @Override
    public Result<UploadVo> uploadImage(MultipartFile file) {
        // 创建WebClient实例
        WebClient webClient = WebClient.create();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Accept", "application/json, text/plain, */*");
        headers.set("appId", "512ab6961a93476aa54e807dd4632ef9");
        headers.set("appSecret", "51154bb6940d0e8f148c0910311a5709a2f9d");
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 创建MultiValueMap作为请求体
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        ByteArrayResource fileResource;
        try {
            // 将MultipartFile转换为ByteArrayResource
            fileResource = new ByteArrayResource(file.getBytes()) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename();
                }
            };
        } catch (IOException e) {
            // 处理文件读取异常
            return Result.build(null, ResultCodeEnum.SYSTEM_ERROR);
        }
        body.add("fileList", fileResource);

        // 发送POST请求
        String url = "http://47.107.52.7:88/member/photo/image/upload";
        UploadResponse response = webClient.method(HttpMethod.POST)
                .uri(url)
                .headers(httpHeaders -> httpHeaders.addAll(headers))
                .body(BodyInserters.fromMultipartData(body))
                .retrieve()
                .bodyToMono(UploadResponse.class)
                .block();

        if (response != null && response.getCode() == 200) {
            UploadVo uploadVo = new UploadVo();
            uploadVo.setImageName(file.getOriginalFilename());
            uploadVo.setImageUrl(response.getData().getImageUrlList()[0]);
            return Result.ok(uploadVo);
        }
        return Result.build(null, ResultCodeEnum.SYSTEM_ERROR);
    }
}
